package pub.pjoc.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.TypeBindings;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author xiongyingqi
 * @since 16-6-8 下午5:34
 */
public abstract class JacksonHelper {
  public static String getJsonString(Object o) {
    ObjectMapper mapper = new ObjectMapper();
    try {
      return mapper.writeValueAsString(o);
    } catch (JsonProcessingException e) {
      return null;
    }
  }

  public static <T> T convertJsonByClass(String json, Class<T> clazz) throws IOException {
    ObjectMapper mapper = newMapper();
    return mapper.readValue(json, clazz);
  }

  public static <T> List<T> convertJsonToListByRawType(String json, Class<T> clazz) throws IOException {
    JavaType listType = getListType(clazz);
    ObjectMapper mapper = newMapper();
    List<T> list = mapper.readValue(json, listType);
    return list;
  }

  public static ObjectMapper newMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return objectMapper;
  }

  /**
   * 获取反序列化的集合类型JavaType
   *
   * @param clazz 元素类型
   * @return {@link JavaType}
   */
  public static JavaType getListType(Class<?> clazz) {
    ObjectMapper mapper = new ObjectMapper();
    JavaType javaType = mapper.constructType(clazz);
    //TypeVariable<?>[] vars = LinkedList.class.getTypeParameters();
    TypeBindings bindings = TypeBindings.create(ArrayList.class, javaType);
    CollectionType collectionType = CollectionType
        .construct(LinkedList.class, bindings, null, null, javaType);
    return collectionType;
  }

}
